package com.vf.cloud.server.artemis.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.dom4j.DocumentException;
import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.SoftPath;
import com.vf.cloud.common.pool.ProssPool;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server implements Runnable{

	// ./artemis create E:\VFCloud\artemis\bin/instance

	/*
	 * PS E:\VFCloud\artemis\bin> ./artemis create E:\VFCloud\artemis/instance
	 * Creating ActiveMQ Artemis instance at: E:\VFCloud\artemis\instance
	 * 
	 * --user: Please provide the default username: root
	 * 
	 * --password: is mandatory with this configuration: Please provide the default
	 * password:
	 * 
	 * 
	 * --allow-anonymous | --require-login: Allow anonymous access?, valid values
	 * are Y,N,True,False y
	 * 
	 * Auto tuning journal ... done! Your system can make 0.05 writes per
	 * millisecond, your journal-buffer-timeout will be 21752000
	 * 
	 * You can now start the broker by executing:
	 * 
	 * "E:\VFCloud\artemis\instance\bin\artemis" run
	 * 
	 * Or you can setup the broker as Windows service and run it in the background:
	 * 
	 * "E:\VFCloud\artemis\instance\bin\artemis-service.exe" install
	 * "E:\VFCloud\artemis\instance\bin\artemis-service.exe" start
	 * 
	 * To stop the windows service:
	 * "E:\VFCloud\artemis\instance\bin\artemis-service.exe" stop
	 * 
	 * To uninstall the windows service
	 * "E:\VFCloud\artemis\instance\bin\artemis-service.exe" uninstall
	 */
	
	boolean isRun=false;

	@Override
	public void run() {
		try {
			String MQTTPid = ProssPool.getPid("2883");
			if (!StrKit.isBlank(MQTTPid)) {
				log.info("MQTTServer >>> 启动MQTTServer成功>>pid:" + MQTTPid);
				ProssPool.put("MQTTServer", MQTTPid);
				isRun=true;
			}else {
				BootstrapXml.update();
				int status = executeCmd(String.format("%s/artemis/instance/bin/artemis run ", SoftPath.path));
				if (0 == status) {
					check();
				}
			}
		} catch (IOException | DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public void stop() {
		try {
			int status = executeCmd(String.format("%s/artemis/instance/bin/artemis stop ", SoftPath.path));
			if (0 == status) {
				check();
			}
		} catch (IOException e) {
		}
	}

	public boolean isRunning() {
		while(true) {
			try {
				if(isRun) {
					break;
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return isRun;
	}
	

	private int executeCmd(String command) throws IOException {
		try {
			if (StrKit.isBlank(ProssPool.getPid("2883"))) {
				Runtime runtime = Runtime.getRuntime();
				Process process = runtime.exec("cmd /c start /b " + command);
//				new Thread(
//						new ConsoleThread(new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))))
//								.start();
				return process.waitFor();
			}
		} catch (InterruptedException e) {
		}
		return -1;
	}

	/**
	 * 控制台
	 *
	 */
	class ConsoleThread implements Runnable {

		private BufferedReader bfr = null;

		public ConsoleThread(BufferedReader bfr) {
			this.bfr = bfr;
		}

		@Override
		public void run() {
			String line = null;
			try {
				while ((line = bfr.readLine()) != null) {
					log.info(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private ScheduledExecutorService scheduledExecutor ;
	public void check() {
		scheduledExecutor = Executors.newScheduledThreadPool(1);
		scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
			@Override
			public void run() {

				String MQTTPid = ProssPool.getPid("2883");

				if (!StrKit.isBlank(MQTTPid)) {
					log.info("MQTTServer >>> 启动MQTTServer成功>>pid:" + MQTTPid);
					ProssPool.put("MQTTServer", MQTTPid);
					isRun=true;
					scheduledExecutor.shutdown();
				}

			}
		}, 0, 1, TimeUnit.SECONDS);
	}


}
